package com.stylefeng.guns.modular.flagglory.service.impl;

import com.fasterxml.uuid.impl.UUIDUtil;
import com.stylefeng.guns.common.persistence.model.InvitationCode;
import com.stylefeng.guns.common.persistence.dao.InvitationCodeMapper;
import com.stylefeng.guns.modular.flagglory.dao.InvitationCodeDao;
import com.stylefeng.guns.modular.flagglory.service.IInvitationCodeService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * lg_邀请码 服务实现类
 * </p>
 *
 * @author stylefeng123
 * @since 2018-01-31
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class InvitationCodeServiceImpl extends ServiceImpl<InvitationCodeMapper, InvitationCode> implements IInvitationCodeService {
    private static final int NUM_LENGTH = 8;
    @Autowired
    private InvitationCodeDao invitationCodeDao;
    @Override
    public boolean distribution(Integer deptId, Integer number) throws Exception {
        InvitationCode invitationCode;
        Random random;
        for (int i = 0; i < number; i++) {
            invitationCode = new InvitationCode();
            invitationCode.setAvailable(true);
            invitationCode.setDeptid(deptId);
            String code = "";
            for (int j = 0; j < NUM_LENGTH; j++) {
                int num = (int) (Math.random() * 10);
                if (num < 1) {
                    num = 0;
                    if (j == 0) {
                        num = 1;
                    }
                }
                code += String.valueOf(num);
            }
            invitationCode.setCode(Integer.parseInt(code));
            invitationCode.setCreatetime(new Date());
            if (!invitationCode.insert()) {
                throw new Exception("分配失败！");
            }
        }
        return true;
    }

    @Override
    public List<Map<String, Object>> selectInvitationByDept() {
        return invitationCodeDao.selectInvitationByDept();
    }
}
